package mongo;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import vo.ClassItem;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

public class ClassDAO {
	public static DBCollection coll;

	public static void main(String[] args) throws Exception {
		int count = getTotalCount();
		System.out.println("count:" + count);
		List<ClassItem> cis = ClassDAO.getAllItems(0, 10);
		System.out.println("size:" + cis);
	}

	public static DBCollection getDBCollection(String collectionName) throws Exception {
		Mongo m = new Mongo("182.50.3.54", 27017);
		DB db = m.getDB("yuqing");
		coll = db.getCollection(collectionName);
		return coll;
	}

	public static List<ClassItem> getAllItems(int start, int pageSize) throws Exception {
		List<ClassItem> cis = new ArrayList<ClassItem>();
		DBCollection coll = ClassDAO.getDBCollection("class");
		BasicDBObject obj = new BasicDBObject();
		DBCursor cursor = coll.find(obj).skip(start).limit(pageSize);
		while (cursor.hasNext()) {
			DBObject it = cursor.next();

			String topicId = (String) it.get("topicId");
			Integer label = (Integer) it.get("label");
			String itemIds = (String) it.get("itemIds");
			ClassItem ci = new ClassItem();
			ci.setTopicId(Integer.parseInt(topicId));
			ci.setLabel(label);
			ci.setItemIds(itemIds);
			cis.add(ci);
		}
		cursor.close();
		return cis;
	}

	public static List<ClassItem> getByItemId(String itemId) throws Exception {
		List<ClassItem> cis = new ArrayList<ClassItem>();
		DBCollection coll = ClassDAO.getDBCollection("class");
		BasicDBObject obj = new BasicDBObject();
		DBCursor cursor = coll.find(obj);

		// 模糊查询itemId
		Pattern pattern = Pattern.compile("^.*" + itemId + ".*$");
		obj.put("itemIds", pattern);

		while (cursor.hasNext()) {
			DBObject it = cursor.next();
			Integer topicId = (Integer) it.get("topicId");
			Integer label = (Integer) it.get("label");
			String itemIds = (String) it.get("itemIds");
//			String ids[] = itemIds.split("_");

			ClassItem ci = new ClassItem();
			ci.setTopicId(topicId);
			ci.setLabel(label);
			ci.setItemIds(itemIds);
			cis.add(ci);
		}
		cursor.close();
		return cis;
	}

	public static int getTotalCount() throws Exception {
		DBCollection coll = getDBCollection("class");
		BasicDBObject obj = new BasicDBObject();
		DBCursor cursor = coll.find(obj);
		int result = cursor.size();
		cursor.close();
		return result;
	}

}